Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
Why is the "this" keyword in this function not giving an error in JavaScript for duplication?

function makeUser() {
  return {
    name: "John",
    ref() {
      return this;
    }
  };
}

let user = makeUser();

alert(user.ref().name);

From what I've learned from thistutorial, they define as the object before dot and since this is the return value of the function, I thought it would be user.

And this tutorial is defining it as the object that is executing the current function.

I think the object that is executing the current function is user. When you replace this by its value it becomes alert(user.user.name);.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The value of "this" doesn't refer to the name of an object, it refers to the object itself. So there is no "duplication" here, you're just returning an object, which happens to be the same object you started with.

This is perhaps clearer if you separate things out:

function makeUser() {
  // Create an object
  let myObject = {
    name: "John"
  };
  // Create a function which returns that object
  let myFunction = function(){ return myObject; };
  // Store the function on the object
  myObject.ref = myFunction;
  // Return the new object
  return myObject;
}

// Create an object
let user = makeUser();

// Get the name from the object
alert(user.name);

// Call the ref() function, which happens to return the same object
let otherUser = user.ref();
// Get the name again
alert(otherUser.name);

// No matter how many times you call .ref() it will return the same object
alert(user.ref().ref().ref().ref().name);

about 4 years ago · Juan Pablo Isaza Denunciar

0

this refers to a object the function function belongs to or window object if it belongs to no objects. in this case ref() function is returning the owner object for e.g.,

when you call ref() it will return like this

{ name: 'John', ref: [Function: ref] }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda